package com.saladin.personalFinancialSystem.controller;

import com.saladin.personalFinancialSystem.model.User;
import com.saladin.personalFinancialSystem.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody User user) {
        User userExist = userService.getUserByUserName(user.getUserName());
        if (userExist != null && userExist.getUserPassword().equals(user.getUserPassword())) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("userId", userExist.getUserId());
            result.put("token", UUID.randomUUID().toString());
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpSession session) {
        session.invalidate();
        return ResponseEntity.ok().build();
    }
}

